package org.glut.wechat.personalcenter.service;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 短信验证码存储验证
 */
@Service
public class VerificationCodeService {
    // 使用ConcurrentHashMap线程安全存储验证码
    private final Map<String, String> codeStore = new ConcurrentHashMap<>();
    private final Map<String, Long> expiryStore = new ConcurrentHashMap<>();

    // 存储验证码
    public void storeCode(String mobile, String code, int minutes) {
        codeStore.put(mobile, code);
        expiryStore.put(mobile, System.currentTimeMillis() + minutes * 60 * 1000);
    }

    // 验证码校验
    public boolean verifyCode(String mobile, String inputCode) {
        String storedCode = codeStore.get(mobile);
        Long expiryTime = expiryStore.get(mobile);

        if (storedCode == null || expiryTime == null) {
            return false; // 验证码不存在
        }

        if (System.currentTimeMillis() > expiryTime) {
            codeStore.remove(mobile);
            expiryStore.remove(mobile);
            return false; // 验证码已过期
        }

        return storedCode.equals(inputCode);
    }

    // 清除验证码
    public void clearCode(String mobile) {
        codeStore.remove(mobile);
        expiryStore.remove(mobile);
    }
}
